import cv2 as cv
# import numpy as np
 
capture = cv.VideoCapture(0)  # 打开摄像头
while True:
    ret, frame = capture.read()  # 返回值，每一帧图像
    # frame = cv.flip(frame, 1)  # 镜像变换左右，上下1或-1
 
    dst = cv.medianBlur(frame, 5)  # 中值滤波
    cv.imshow("median video", dst)
 
    # hsv = cv.cvtColor(dst, cv.COLOR_BGR2HSV)
    # cv.imshow("hsv", hsv)
    # lower_hsv = np.array([0, 0, 221])
    # upper_hsv = np.array([180, 30, 255])
    # extract_white = cv.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)  # inRange API进行颜色提取
    # cv.imshow("extract_red demo", extract_white)
 
    canny = cv.Canny(dst, 40, 80)
    cv.imshow('canny video', canny)
 
    # 霍夫变换圆检测
    circles = cv.HoughCircles(canny, cv.HOUGH_GRADIENT, 1, 50, param1=80, param2=30, minRadius=60, maxRadius=150)
    # 输出返回值，方便查看类型
    print(circles)
 
    # 输出检测到圆的个数
    print("Sum:%d" % len(circles[0]))
 
    # 根据检测到圆的信息，画出每一个圆
    for circle in circles[0]:
        # 坐标行列(就是圆心)
        x = int(circle[0])
        y = int(circle[1])
        # 半径
        r = int(circle[2])
        # 在原图用指定颜色圈出圆，参数设定为int所以圈画存在误差
        img = cv.circle(frame, (x, y), r, (0, 0, 255), 1, 8, 0)
        # 圆的基本信息
        print("x=%d, y=%d, r=%d" % (x, y, r))
    cv.imshow("video", img)
 
    key = cv.waitKey(1)
    if key == 27:  # Esc退出
        break
 
# cv.destroyAllWindows()
